
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ChatFile extends File {

    public ChatFile(String name) {
        super(name);
    }

    public ChatFile(File f) {
        super(f.getAbsolutePath());
    }

    // Append encrypted text to the end of the chat file. This method does
    // nothing if the file write fails.
    public void append(String text) {
        try {
            FileOutputStream out = new FileOutputStream(this, true);
            byte[] b = text.getBytes();
            encrypt(b);
            out.write(b);
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void reWriteUsers(String text, String loginString, String replace)
            throws IOException {
        FileOutputStream out = new FileOutputStream(this);
        byte[] b = text.replace(loginString, replace).getBytes();
        encrypt(b);
        out.write(b);
        out.close();
        System.out.println(loginString);
    }

    // Get the data from the chat file, and decrypt it.
    public String getText() throws IOException {
        FileInputStream input = new FileInputStream(this);
        byte[] buffer = new byte[input.available()];
        input.read(buffer);
        input.close();
        decrypt(buffer);
        return new String(buffer);
    }

    // encrypt and decrypt are the same right now, thanks to the beauty of xor
    private void encrypt(byte[] b) {
        for (int i = 0; i < b.length; i++) {
            b[i] = (byte) (b[i] ^ 0x7B); // 0x7B is random, no particular reasoning
        }
    }

    private void decrypt(byte[] b) {
        for (int i = 0; i < b.length; i++) {
            b[i] = (byte) (b[i] ^ 0x7B);
        }
    }

    // for convenience...
    public String getNameNoExtension() {
        // remove extension
        return getName().replaceAll("\\.[^.]+$", "");
    }
}
